package com.iims.system.service.impl;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.iims.common.constant.UserConstants;
import com.iims.common.core.domain.entity.SysRole;
import com.iims.common.exception.CustomException;
import com.iims.system.domain.SysGroup;
import com.iims.system.domain.SysGroupRole;
import com.iims.system.domain.SysGroupUser;
import com.iims.system.mapper.SysGroupMapper;
import com.iims.system.mapper.SysGroupRoleMapper;
import com.iims.system.mapper.SysGroupUserMapper;
import com.iims.system.service.ISysGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author fanpei
 * @date 2021/5/26 17:10
 */
@Service
public class SysGroupServiceImpl extends ServiceImpl<SysGroupMapper, SysGroup> implements ISysGroupService {

    @Autowired
    private SysGroupRoleMapper groupRoleMapper;
    @Autowired
    private SysGroupUserMapper groupUserMapper;

    @Override
    public List<SysGroup> selectGroupList(SysGroup group) {
        return list(new LambdaQueryWrapper<SysGroup>()
                .like(StrUtil.isNotBlank(group.getGroupCode()), SysGroup::getGroupCode, group.getGroupCode())
                .eq(StrUtil.isNotBlank(group.getStatus()), SysGroup::getStatus, group.getStatus())
                .like(StrUtil.isNotBlank(group.getGroupName()), SysGroup::getGroupName, group.getGroupName()));
    }

    /**
     * 查询所有分组
     *
     * @return 分组列表
     */
    @Override
    public List<SysGroup> selectGroupAll() {
        return list();
    }

    /**
     * 通过分组ID查询分组信息
     *
     * @param groupId 分组ID
     * @return 角色对象信息
     */
    @Override
    public SysGroup selectGroupById(Long groupId) {
        return getById(groupId);
    }

    /**
     * 根据用户ID获取分组选择框列表
     *
     * @param userId 用户ID
     * @return 选中分组ID列表
     */
    @Override
    public List<SysGroup> selectGroupListByUserId(Long userId) {
        return baseMapper.selectGroupListByUserId(userId);
    }

    /**
     * 根据分组id获取分组列表
     *
     * @param groupId
     * @return
     */
    @Override
    public List<SysRole> selectRoleListByGroupId(Long groupId) {
        return baseMapper.selectRoleListByGroupId(groupId);
    }

    /**
     * 根据用户ID获取岗位选择框列表
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysGroup> selectExcludeGroupListByUserId(Long userId) {
        return baseMapper.selectExcludeGroupListByUserId(userId);
    }

    /**
     * @param groupId
     * @return
     */
    @Override
    public List<SysRole> selectExcludeRoleListByGroupId(Long groupId) {
        return baseMapper.selectExcludeRoleListByGroupId(groupId);
    }

    /**
     * 校验分组名称是否唯一
     *
     * @param group 分组信息
     * @return 结果
     */
    @Override
    public String checkGroupNameUnique(SysGroup group) {
        Long groupId = Validator.isNull(group.getGroupId()) ? -1L : group.getGroupId();
        SysGroup info = getOne(new LambdaQueryWrapper<SysGroup>()
                .eq(SysGroup::getGroupName, group.getGroupName()).last("limit 1"));
        if (Validator.isNotNull(info) && info.getGroupId().longValue() != groupId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验分组编码是否唯一
     *
     * @param group 分组信息
     * @return 结果
     */
    @Override
    public String checkGroupCodeUnique(SysGroup group) {
        Long groupId = Validator.isNull(group.getGroupId()) ? -1L : group.getGroupId();
        SysGroup info = getOne(new LambdaQueryWrapper<SysGroup>()
                .eq(SysGroup::getGroupCode, group.getGroupCode()).last("limit 1"));
        if (Validator.isNotNull(info) && info.getGroupId().longValue() != groupId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 通过分组ID查询分组使用数量
     *
     * @param groupId 分组ID
     * @return 结果
     */
    @Override
    public int countGroupById(Long groupId) {
        return baseMapper.selectUseCount(groupId);
    }


    /**
     * 删除分组信息
     *
     * @param groupId 分组ID
     * @return 结果
     */
    @Override
    public int deleteGroupById(Long groupId) {
        return baseMapper.deleteById(groupId);
    }

    /**
     * 批量删除分组信息
     *
     * @param groupIds 需要删除的分组ID
     * @return 结果
     * @throws Exception 异常
     */
    @Override
    public int deleteGroupByIds(Long[] groupIds) {
        for (Long groupId : groupIds) {
            SysGroup group = selectGroupById(groupId);
            if (countGroupById(groupId) > 0) {
                throw new CustomException(String.format("%1$s已分配,不能删除", group.getGroupName()));
            }
        }
        return baseMapper.deleteBatchIds(Arrays.asList(groupIds));
    }

    /**
     * 新增保存分组信息
     *
     * @param group 分组信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertGroup(SysGroup group) {
        int rows = baseMapper.insert(group);
        insertGroupRole(group);
        insertGroupUser(group);
        return rows;

    }

    /**
     * 修改分组信息
     *
     * @param group 分组信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateGroup(SysGroup group) {
        Long groupId = group.getGroupId();
        groupUserMapper.delete(new LambdaQueryWrapper<SysGroupUser>().eq(SysGroupUser::getGroupId, groupId));
        insertGroupUser(group);
        groupRoleMapper.delete(new LambdaQueryWrapper<SysGroupRole>().eq(SysGroupRole::getGroupId, groupId));
        insertGroupRole(group);
        return baseMapper.updateById(group);
    }

    public int insertGroupRole(SysGroup group) {
        int rows = 0;
        if (Validator.isNotNull(group.getRoleIds())) {
            List<SysGroupRole> list = new ArrayList<>();
            for (Long roleId : group.getRoleIds()) {
                SysGroupRole gr = new SysGroupRole();
                gr.setGroupId(group.getGroupId());
                gr.setRoleId(roleId);
                list.add(gr);
            }
            if (list.size() > 0) {
                for (SysGroupRole sysGroupRole : list) {
                    rows += groupRoleMapper.insert(sysGroupRole);
                }
            }
        }
        return rows;
    }

    public int insertGroupUser(SysGroup group) {
        int rows = 0;
        if (Validator.isNotNull(group.getUserIds())) {
            List<SysGroupUser> list = new ArrayList<>();
            for (Long userId : group.getUserIds()) {
                SysGroupUser gu = new SysGroupUser();
                gu.setGroupId(group.getGroupId());
                gu.setUserId(userId);
                list.add(gu);
            }
            if (list.size() > 0) {
                for (SysGroupUser sysGroupUser : list) {
                    rows += groupUserMapper.insert(sysGroupUser);
                }
            }
        }
        return rows;
    }
}
